<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>Collection 记录管理</title>
  <!-- 1. jQuery -->
  <script src="{{ url_for('static', filename='js/jquery-3.5.1.min.js') }}"></script>
  <!-- 2. Popper.js -->
  <script src="{{ url_for('static', filename='js/popper.min.js') }}"></script>
  <!-- 3. Bootstrap CSS -->
  <link rel="stylesheet" href="{{ url_for('static', filename='css/bootstrap.min.css') }}">
  <!-- 4. Bootstrap JS -->
  <script src="{{ url_for('static', filename='js/bootstrap.min.js') }}"></script>
  <!-- 5. Font Awesome -->
  <link rel="stylesheet" href="{{ url_for('static', filename='css/all.min.css') }}">
  <style>
    .search-container {
      margin: 20px 0;
    }
    .actions-column {
      width: 150px;
    }
    .action-btn {
      margin: 0 2px;
    }
    .document-cell {
      max-width: 300px;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }
    .modal-lg {
      max-width: 80%;
    }
    .full-content {
      white-space: pre-wrap;
      word-break: break-word;
    }
    
    /* 复选框样式 */
    .record-checkbox, #select-all {
      width: 18px;
      height: 18px;
      cursor: pointer;
    }
    
    /* 表格第一列（复选框列）宽度 */
    table th:first-child,
    table td:first-child {
      width: 40px;
      text-align: center;
    }
    
    /* 按钮间距 */
    .btn + .btn {
      margin-left: 10px;
    }
    
    /* 按钮组样式 */
    .d-flex {
      display: flex !important;
    }
    
    .justify-content-between {
      justify-content: space-between !important;
    }
  </style>
</head>
<body>
<div class="container">
  <h1 class="mt-4">Collection: {{ collection_name }}</h1>
  
  <!-- 修改按钮组 -->
  <div class="mb-3 d-flex justify-content-between">
    <div>
      <a href="/" class="btn btn-secondary">
        <i class="fas fa-arrow-left"></i> 返回
      </a>
      <button class="btn btn-danger ms-2" id="batch-delete-btn" style="display:none; margin-left: 10px;">
        <i class="fas fa-trash"></i> 批量删除
      </button>
    </div>
    <button class="btn btn-primary" id="add-record-btn">
      <i class="fas fa-plus"></i> 新建记录
    </button>
  </div>
  
  <!-- 查询控制区域 -->
  <div class="card mb-4">
    <div class="card-body">
      <ul class="nav nav-tabs" id="searchTabs">
        <li class="nav-item">
          <a class="nav-link active" data-toggle="tab" href="#idSearch">ID 查询</a>
        </li>
        <li class="nav-item">
          <a class="nav-link" data-toggle="tab" href="#hybridSearch">混合查询</a>
        </li>
      </ul>
      
      <div class="tab-content mt-3">
        <!-- ID 查询表单 -->
        <div class="tab-pane fade show active" id="idSearch">
          <div class="form-group">
            <input type="text" class="form-control" id="search-record-id" placeholder="输入记录 ID">
          </div>
          <button class="btn btn-primary" id="search-by-id">查询</button>
        </div>
        
        <!-- 混合查询表单 -->
        <div class="tab-pane fade" id="hybridSearch">
          <div class="form-group">
            <label>语义查询文本</label>
            <input type="text" class="form-control" id="query-text" placeholder="输入查询文本，将转换为向量进行相似度搜索">
          </div>
          
          <div class="form-group">
            <label>最大返回条数</label>
            <input type="number" class="form-control" id="n-results" value="20" min="1" max="1000">
          </div>
          
          <div class="form-group">
            <label>文档内容过滤</label>
            <input type="text" class="form-control" id="document-filter" placeholder="输入关键词过滤文档内容">
          </div>
          
          <div class="form-group">
            <label>元数据过滤</label>
            <div id="metadata-filters">
              <!-- 动态添加的元数据过滤条件 -->
            </div>
            <button class="btn btn-secondary btn-sm" id="add-metadata-filter">
              <i class="fas fa-plus"></i> 添加元数据过滤
            </button>
          </div>
          
          <button class="btn btn-primary" id="search-hybrid">查询</button>
        </div>
      </div>
    </div>
  </div>

  <!-- 表格区域 -->
  <div id="records-table">
    <table class="table table-striped">
      <thead>
        <tr>
          <th width="40">
            <input type="checkbox" id="select-all">
          </th>
          <th>ID</th>
          <th>Document</th>
          <th>Metadata</th>
          <th>Distance</th>
          <th class="actions-column">操作</th>
        </tr>
      </thead>
      <tbody>
        <!-- 通过 AJAX 动态加载数据 -->
      </tbody>
    </table>
  </div>

  <!-- 添加模态框 -->
  <div class="modal fade" id="recordModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title" id="recordModalLabel">编辑记录</h5>
          <button type="button" class="close" data-dismiss="modal">
            <span>&times;</span>
          </button>
        </div>
        <div class="modal-body">
          <form id="recordForm">
            <input type="hidden" id="record-id">
            <div class="form-group">
              <label for="record-document">Document</label>
              <textarea class="form-control" id="record-document" rows="5"></textarea>
            </div>
            <div class="form-group">
              <label for="record-metadata">Metadata (JSON)</label>
              <textarea class="form-control" id="record-metadata" rows="3"></textarea>
            </div>
          </form>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
          <button type="button" class="btn btn-primary" id="save-record">保存</button>
        </div>
      </div>
    </div>
  </div>

  <!-- 添加内容查看模态框 -->
  <div class="modal fade" id="viewDocumentModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title">Document 内容</h5>
          <button type="button" class="close" data-dismiss="modal">
            <span>&times;</span>
          </button>
        </div>
        <div class="modal-body">
          <div class="full-content"></div>
        </div>
      </div>
    </div>
  </div>

  <!-- 分页控件 -->
  <nav aria-label="Page navigation">
    <ul class="pagination justify-content-center" id="pagination">
    </ul>
  </nav>
</div>

<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.5.4/dist/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"></script>
<script>
let currentPage = 1;
const pageSize = 10;
let currentSearchType = '';  // 保存当前检索类型
let currentParams = {};      // 保存当前查询参数

function loadRecords(page = 1, searchType = 'id', params = {}) {
  currentPage = page;
  currentSearchType = searchType;
  currentParams = params;
  
  const queryParams = new URLSearchParams({
    page: currentPage,
    page_size: pageSize,
    search_type: searchType,
    ...params
  });

  $.getJSON(`/api/collections/{{ collection_name }}/records?${queryParams}`)
    .done(function(data) {
      renderTable(data.records);
      renderPagination(data.total);
    })
    .fail(function(err) {
      alert('查询失败: ' + (err.responseJSON?.error || '未知错误'));
    });
}

// 使用这个版本的 searchRecords 保持 currentPage 的传递，不强制重置
function searchRecords(searchType, params = {}) {
  // 如果未指定 page，则重置为第一页，否则使用传递的 page 参数
  if (params.page) {
    currentPage = params.page;
  } else {
    currentPage = 1;
    params.page = 1;
  }
  currentSearchType = searchType;
  currentParams = params;
  
  const queryParams = new URLSearchParams({
    page: currentPage,
    page_size: pageSize,
    search_type: searchType,
    ...params
  });
  
  $.getJSON(`/api/collections/{{ collection_name }}/records?${queryParams}`)
    .done(function(data) {
      renderTable(data.records);
      renderPagination(data.total);
    })
    .fail(function(err) {
      alert('查询失败: ' + (err.responseJSON?.error || '未知错误'));
    });
}

function updateBatchDeleteButton() {
  const checkedCount = $('.record-checkbox:checked').length;
  $('#batch-delete-btn').toggle(checkedCount > 0);
  // 更新全选框状态
  const totalCount = $('.record-checkbox').length;
  $('#select-all').prop('checked', checkedCount > 0 && checkedCount === totalCount);
}

function renderTable(records) {
  let html = '';
  records.forEach(function(record) {
    // 处理 metadata 的显示：如果为空或 null 则显示为空字符串
    const metadataDisplay = record.metadata && Object.keys(record.metadata).length > 0 
      ? JSON.stringify(record.metadata) 
      : '';
    const metadataAttr = record.metadata && Object.keys(record.metadata).length > 0 
      ? encodeURIComponent(JSON.stringify(record.metadata))
      : '';

    html += `<tr>
      <td>
        <input type="checkbox" class="record-checkbox" data-id="${record.id}">
      </td>
      <td>${record.id}</td>
      <td class="document-cell">
        <a href="#" class="view-document" data-content="${encodeURIComponent(record.document)}">
          ${record.document}
        </a>
      </td>
      <td>${metadataDisplay}</td>
      <td>${record.distance !== null ? record.distance.toFixed(4) : '-'}</td>
      <td class="actions-column">
        <button class="btn btn-sm btn-info action-btn edit-record" 
                data-id="${record.id}"
                data-document="${encodeURIComponent(record.document)}"
                data-metadata="${metadataAttr}"
                title="编辑">
          <i class="fas fa-edit"></i>
        </button>
        <button class="btn btn-sm btn-danger action-btn delete-record" 
                data-id="${record.id}" title="删除">
          <i class="fas fa-trash"></i>
        </button>
      </td>
    </tr>`;
  });
  $('#records-table tbody').html(html);
  updateBatchDeleteButton();
}

function renderPagination(total) {
    const totalPages = Math.ceil(total / pageSize);
    let html = `
        <li class="page-item ${currentPage === 1 ? 'disabled' : ''}">
            <a class="page-link" href="#" data-page="${currentPage-1}" aria-label="Previous">
                <span aria-hidden="true">&laquo;</span>
            </a>
        </li>`;
    
    let startPage = Math.max(1, currentPage - 2);
    let endPage = Math.min(totalPages, currentPage + 2);
    
    if (startPage > 1) {
        html += `
            <li class="page-item">
                <a class="page-link" href="#" data-page="1">1</a>
            </li>`;
        if (startPage > 2) {
            html += `
                <li class="page-item disabled">
                    <span class="page-link">...</span>
                </li>`;
        }
    }
    
    for (let i = startPage; i <= endPage; i++) {
        html += `
            <li class="page-item ${i === currentPage ? 'active' : ''}">
                <a class="page-link" href="#" data-page="${i}">${i}</a>
            </li>`;
    }
    
    if (endPage < totalPages) {
        if (endPage < totalPages - 1) {
            html += `
                <li class="page-item disabled">
                    <span class="page-link">...</span>
                </li>`;
        }
        html += `
            <li class="page-item">
                <a class="page-link" href="#" data-page="${totalPages}">${totalPages}</a>
            </li>`;
    }
    
    html += `
        <li class="page-item ${currentPage === totalPages ? 'disabled' : ''}">
            <a class="page-link" href="#" data-page="${currentPage+1}" aria-label="Next">
                <span aria-hidden="true">&raquo;</span>
            </a>
        </li>`;
    
    $('#pagination').html(html);
}

$(document).ready(function() {
  // 初始加载
  loadRecords();

  // 搜索功能点击事件
  $('#search-by-id').click(function() {
    const recordId = $('#search-record-id').val();  // 修改这里
    searchRecords('id', { id: recordId });
  });

  $('#search-hybrid').click(function() {
    const queryText = $('#query-text').val();
    const documentFilter = $('#document-filter').val();
    const nResults = parseInt($('#n-results').val()) || 20;
    
    const metadataFilters = {};
    $('.metadata-filter-row').each(function() {
      const key = $(this).find('.metadata-key').val();
      const value = $(this).find('.metadata-value').val();
      if (key && value) {
        metadataFilters[key] = value;
      }
    });
    
    const params = {};
    if (queryText) params.query_text = queryText;
    if (documentFilter) params.document_filter = documentFilter;
    if (Object.keys(metadataFilters).length > 0) {
      params.metadata_filter = JSON.stringify(metadataFilters);
    }
    params.n_results = nResults;
    
    searchRecords('hybrid', params);
  });

  // 分页点击事件：调用 searchRecords，传入当前搜索条件和选中的页码
  $('#pagination').on('click', '.page-link', function(e) {
    e.preventDefault();
    if ($(this).parent().hasClass('disabled')) return;
    const page = $(this).data('page');
    if (page && page !== currentPage) {
      let params = { ...currentParams, page };
      if (currentSearchType === 'id') {
        const recordId = $('#search-record-id').val();  // 修改这里
        if (recordId) params.id = recordId;
      } else {
        const queryText = $('#query-text').val();
        const documentFilter = $('#document-filter').val();
        
        const metadataFilters = {};
        $('.metadata-filter-row').each(function() {
          const key = $(this).find('.metadata-key').val();
          const value = $(this).find('.metadata-value').val();
          if (key && value) {
            metadataFilters[key] = value;
          }
        });
        
        if (queryText) params.query_text = queryText;
        if (documentFilter) params.document_filter = documentFilter;
        if (Object.keys(metadataFilters).length > 0) {
          params.metadata_filter = JSON.stringify(metadataFilters);
        }
        if (currentParams.n_results) params.n_results = currentParams.n_results;
      }
      searchRecords(currentSearchType, params);
    }
  });

  // 删除记录
  $('#records-table').on('click', '.delete-record', function() {
    const id = $(this).data('id');
    if(confirm('确定要删除这条记录吗？')) {
      $.ajax({
        url: `/api/collections/{{ collection_name }}/records/${id}`,
        method: 'DELETE',
        success: function() {
          loadRecords(currentPage, currentSearch);
        }
      });
    }
  });

  // 查看完整内容
  $('#records-table').on('click', '.view-document', function(e) {
    e.preventDefault();
    const content = decodeURIComponent($(this).data('content'));
    $('#viewDocumentModal .full-content').text(content);
    $('#viewDocumentModal').modal('show');
  });

  // 修改新增记录按钮点击事件
  $('#add-record-btn').click(function() {
    $('#recordModalLabel').text('新增记录');
    $('#record-id').val('');
    $('#record-document').val('');
    $('#record-metadata').val('');  // 改为空字符串
    $('#recordModal').modal('show');
  });

  // 修改编辑记录点击事件
  $('#records-table').on('click', '.edit-record', function() {
    const id = $(this).data('id');
    const document = decodeURIComponent($(this).data('document'));
    const metadata = decodeURIComponent($(this).data('metadata'));
    
    $('#recordModalLabel').text('编辑记录');
    $('#record-id').val(id);
    $('#record-document').val(document);
    // 如果 metadata 是 "{}" 则显示为空
    $('#record-metadata').val(metadata === '{}' ? '' : metadata);
    $('#recordModal').modal('show');
  });

  // 修改保存记录按钮点击事件
  $('#save-record').click(function() {
    const id = $('#record-id').val();
    const document = $('#record-document').val();
    const metadataStr = $('#record-metadata').val().trim();
    
    // 构造请求数据
    const data = {
        document: document
    };

    // 只有当 metadata 不为空时才解析并添加到请求数据中
    if (metadataStr) {
        try {
            data.metadata = JSON.parse(metadataStr);
        } catch(e) {
            alert('Metadata 必须是有效的 JSON 格式');
            return;
        }
    }

    const method = id ? 'PUT' : 'POST';
    const url = id 
        ? `/api/collections/{{ collection_name }}/records/${id}`
        : `/api/collections/{{ collection_name }}/records`;

    $.ajax({
        url: url,
        method: method,
        contentType: 'application/json',
        data: JSON.stringify(data),
        success: function() {
            $('#recordModal').modal('hide');
            loadRecords(currentPage, currentSearch);
        },
        error: function(err) {
            alert('保存失败: ' + err.responseJSON?.error || '未知错误');
        }
    });
  });

  // 全选/取消全选
  $('#select-all').change(function() {
    const isChecked = $(this).prop('checked');
    $('.record-checkbox').prop('checked', isChecked);
    updateBatchDeleteButton();
  });

  // 单个复选框变化时更新批量删除按钮状态
  $('#records-table').on('change', '.record-checkbox', function() {
    updateBatchDeleteButton();
  });

  // 更新批量删除按钮显示状态
  function updateBatchDeleteButton() {
    const checkedCount = $('.record-checkbox:checked').length;
    $('#batch-delete-btn').toggle(checkedCount > 0);
    // 更新全选框状态
    const totalCount = $('.record-checkbox').length;
    $('#select-all').prop('checked', checkedCount > 0 && checkedCount === totalCount);
  }

  // 批量删除按钮点击事件
  $('#batch-delete-btn').click(function() {
    const selectedIds = $('.record-checkbox:checked').map(function() {
      return $(this).data('id');
    }).get();

    if (selectedIds.length === 0) return;

    if (confirm(`确定要删除选中的 ${selectedIds.length} 条记录吗？`)) {
      $.ajax({
        url: `/api/collections/{{ collection_name }}/records`,
        method: 'DELETE',
        contentType: 'application/json',
        data: JSON.stringify({ ids: selectedIds }),
        success: function() {
          alert('批量删除成功！');
          loadRecords(currentPage, currentSearchType, currentParams);
        },
        error: function(err) {
          alert('删除失败: ' + (err.responseJSON?.error || '未知错误'));
          loadRecords(currentPage, currentSearchType, currentParams);
        }
      });
    }
  });
});

// 动态添加元数据过滤条件
$('#add-metadata-filter').click(function() {
  const filterRow = $(`
    <div class="input-group mb-2 metadata-filter-row">
      <input type="text" class="form-control metadata-key" placeholder="元数据字段">
      <input type="text" class="form-control metadata-value" placeholder="字段值">
      <div class="input-group-append">
        <button class="btn btn-outline-danger remove-filter">
          <i class="fas fa-times"></i>
        </button>
      </div>
    </div>
  `);
  $('#metadata-filters').append(filterRow);
});

// 删除元数据过滤条件
$(document).on('click', '.remove-filter', function() {
  $(this).closest('.metadata-filter-row').remove();
});

</script>
</body>
</html>
